import React, { useState, useEffect } from 'react';
import type { FC } from 'react';
import { Card, Table, Typography, Space, Select, Pagination, Button, Modal, Form, Input, DatePicker,Divider,Radio } from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { fetchConcepts, createConcept, deleteConcept, updateConcept, fetchEssays } from '../../services/manipulate.ts';
import './concept.css';

const { Option } = Select;
const { Text } = Typography;

const Concept: FC = () => {
  const [concepts, setConcepts] = useState<Array<any>>([]);
  const [filteredConcepts, setFilteredConcepts] = useState<Array<any>>([]);
  const [selectedConcept, setSelectedConcept] = useState(null);
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [categories, setCategories] = useState<string[]>([]);
  const [essays, setEssays] = useState<Array<any>>([]);
  const [selectedEssayContent, setSelectedEssayContent] = useState<string>('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [isEditing, setIsEditing] = useState<boolean>(false);
  const [form] = Form.useForm();

  useEffect(() => {
    const loadData = async () => {
      try {
        // 获取概念数据
        const conceptsData = await fetchConcepts();
        console.log('concepts data:', conceptsData);
        
        // 设置概念数据
        setConcepts(conceptsData || []);
        setFilteredConcepts(conceptsData || []);
        
        // 提取唯一的分类值
        const uniqueCategories = Array.from(
          new Set((conceptsData || []).map(item => item.category))
        ).filter(Boolean); // 过滤掉空值
        console.log('uniqueCategories:', uniqueCategories);
        
        setCategories(uniqueCategories);
        
        setPagination({
          ...pagination,
          total: (conceptsData || []).length,
        });
        
        // 获取文章数据
        const essaysData = await fetchEssays();
        console.log('essays data:', essaysData);
        setEssays(essaysData || []);
      } catch (error) {
        console.error('Failed to fetch data:', error);
        setConcepts([]);
        setFilteredConcepts([]);
        setCategories([]);
        setEssays([]);
        setPagination({
          ...pagination,
          total: 0,
        });
      }
    };
    loadData();
  }, []);

  const handleTableChange = (pagination) => {
    setPagination(pagination);
  };
  
  const handleCategoryChange = (value: string | null) => {
    setSelectedCategory(value);
    
    if (!value) {
      // 如果没有选择分类，显示所有数据
      setFilteredConcepts(concepts);
      setPagination({
        ...pagination,
        total: concepts.length,
        current: 1,
      });
    } else {
      // 根据选择的分类过滤数据
      const filtered = concepts.filter(item => item.category === value);
      setFilteredConcepts(filtered);
      setPagination({
        ...pagination,
        total: filtered.length,
        current: 1,
      });
    }
  };

  const handleCreateConcept = async (values) => {
    try {
      const currentDate = new Date().toISOString().split('T')[0];
      const payload = {
        ...values,
        created_at: currentDate,
      };
      console.log('payload:', payload);
      
      if (isEditing) {
        console.log('isEditing:', isEditing);
        console.log('selectedConcept:', selectedConcept);
        await updateConcept(selectedConcept.id,payload);
      } else {
        await createConcept(payload);
      }
      
      setIsModalVisible(false);
      setIsEditing(false);
      form.resetFields();
      
      // 重新获取概念数据
      const conceptsData = await fetchConcepts();
      setConcepts(conceptsData || []);
      
      // 提取唯一的分类值
      const uniqueCategories = Array.from(
        new Set((conceptsData || []).map(item => item.category))
      ).filter(Boolean);
      setCategories(uniqueCategories);
      
      // 重新获取文章数据
      const essaysData = await fetchEssays();
      setEssays(essaysData || []);
      console.log('essaysData:',essaysData)
      
      // 根据当前选中的分类重新过滤数据
      if (selectedCategory) {
        const filtered = (conceptsData || []).filter(item => item.category === selectedCategory);
        setFilteredConcepts(filtered);
        setPagination({
          ...pagination,
          total: filtered.length,
          current: 1,
        });
      } else {
        setFilteredConcepts(conceptsData || []);
        setPagination({
          ...pagination,
          total: (conceptsData || []).length,
          current: 1,
        });
      }
    } catch (error) {
      console.error('Failed to handle concept:', error);
    }
  };

  const handleDeleteConcept = async (id) => {
    try {
      // 删除概念
      await deleteConcept(id);
      
      // 重新获取概念数据
      const conceptsData = await fetchConcepts();
      setConcepts(conceptsData || []);
      
      // 提取唯一的分类值
      const uniqueCategories = Array.from(
        new Set((conceptsData || []).map(item => item.category))
      ).filter(Boolean);
      setCategories(uniqueCategories);
      
      // 重新获取文章数据
      const essaysData = await fetchEssays();
      setEssays(essaysData || []);
      
      // 根据当前选中的分类重新过滤数据
      if (selectedCategory) {
        const filtered = (conceptsData || []).filter(item => item.category === selectedCategory);
        setFilteredConcepts(filtered);
        setPagination({
          ...pagination,
          total: filtered.length,
          current: 1,
        });
      } else {
        setFilteredConcepts(conceptsData || []);
        setPagination({
          ...pagination,
          total: (conceptsData || []).length,
          current: 1,
        });
      }
    } catch (error) {
      console.error('Failed to delete concept:', error);
    }
  };
  
  // 处理点击概念行，显示关联文章全文
  const handleConceptRowClick = (record) => {
    setSelectedConcept(record);
    
    // 根据关联文章标题查找对应的文章全文
    if (record && record.essay_title && essays.length > 0) {
      const relatedEssay = essays.find(essay => essay.title === record.essay_title);
      if (relatedEssay) {
        setSelectedEssayContent(relatedEssay.full_text || '该文章暂无内容');
      } else {
        setSelectedEssayContent('未找到关联文章内容');
      }
    } else {
      setSelectedEssayContent('');
    }
  };

  const columns = [
    {
      title: '序号',
      key: 'index',
      render: (text, record, index) => index + 1,
      width: 80,
    },
    {
      title: '概念分类',
      align: 'center',
      dataIndex: 'category',
      key: 'category',
      width: 160,
    },
    {
      title: '概念名称',
      align: 'center',
      dataIndex: 'concept_name',
      key: 'concept_name',
      width: 200,
    },
    {
      title: '描述',
      align: 'center',
      dataIndex: 'concept_description',
      key: 'concept_description',
    },
    {
      title: '关联文章',
      align: 'center',
      dataIndex: 'essay_title',
      key: 'essay_title',
      width: 200,
    },
    {
      title: '日期',
      align: 'center',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 120,
      render: (text) => {
        if (!text) return '-';
        const date = new Date(text);
        return date instanceof Date && !isNaN(date.getTime()) 
          ? `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}` 
          : text;
      },
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      width: 80,
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="text" 
            icon={<EditOutlined />} 
            onClick={() => {
              form.setFieldsValue(record);
              setIsEditing(true);
              setIsModalVisible(true);
            }}
            style={{ color: '#ccd6f6' }}
          />
          <Button 
            type="text" 
            icon={<DeleteOutlined />} 
            onClick={() => handleDeleteConcept(record.id)}
            style={{ color: '#ff4d4f' }}
          />
        </Space>
      ),
    },
  ];

  // 自定义卡片样式
  const cardStyle = {
    backgroundColor: '#112240',
    borderColor: '#233554',
  };
  
  const cardHeadStyle = {
    backgroundColor: '#112240',
    borderBottomColor: '#233554',
  };
  
  const cardBodyStyle = {
    backgroundColor: '#112240',
  };

  return (
    <div style={{ padding: '20px', backgroundColor: '#0a192f' }}>
      <Card 
        style={{ 
          marginBottom: '20px', 
          width: '500px',
          ...cardStyle
        }}
        headStyle={cardHeadStyle}
        bodyStyle={cardBodyStyle}
        className="dark-theme-card"
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px'  }}>
          <span>选择概念分类</span>
          <Select 
            placeholder="请选择概念分类" 
            style={{ flex: 1, backgroundColor: '#112240', color: '#ccd6f6', borderColor: '#233554' }}
            onChange={handleCategoryChange}
            value={selectedCategory}
            allowClear
          >
            {categories.map(category => (
              <Option key={category} value={category}>{category}</Option>
            ))}
          </Select>
          <Button 
            type="primary"
            onClick={() => handleCategoryChange(null)}
            style={{ 
              backgroundColor: '#112240', 
              borderColor: '#233554', 
              color: '#ccd6f6',
              whiteSpace: 'nowrap'
            }}
          >
            显示全部记录
          </Button>
        </div>
      </Card>

      <div style={{ width: '100%' }}>
        <Card 
          title={
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span>概念列表</span>
              <Button 
                type="primary" 
                onClick={() => {
                  form.resetFields();
                  setIsEditing(false);
                  setIsModalVisible(true);
                }}
                style={{ backgroundColor: '#112240', borderColor: '#233554', color: '#ccd6f6' }}
              >
                新增概念
              </Button>
            </div>
          }
          style={{ 
            marginBottom: '20px',
            ...cardStyle
          }}
          headStyle={cardHeadStyle}
          bodyStyle={cardBodyStyle}
          className="dark-theme-card"
        >
          <Table
            columns={columns}
            dataSource={Array.isArray(filteredConcepts) ? filteredConcepts : []}
            pagination={pagination}
            onChange={handleTableChange}
            rowKey="id"
            onRow={(record) => ({
              onClick: () => handleConceptRowClick(record),
            })}
            className="dark-theme-table"
            style={{ backgroundColor: '#112240', color: '#ccd6f6' }}
            rowClassName={() => 'dark-theme-table-row'}
            locale={{
              emptyText: <div style={{ padding: '20px', backgroundColor: '#112240', color: '#8892b0' }}>暂无数据</div>
            }}
          />
        </Card>

        <Card 
          title="关联文章全文内容"
          style={cardStyle}
          headStyle={cardHeadStyle}
          bodyStyle={cardBodyStyle}
          className="dark-theme-card"
        >
          <div style={{ padding: '10px' }}>
            {selectedConcept && (
              <div style={{ marginBottom: '10px' }}>
                <Text strong style={{ color: '#ccd6f6', marginRight: '10px' }}>当前概念:</Text>
                <Text style={{ color: '#8892b0' }}>{selectedConcept.concept_name}</Text>
              </div>
            )}
            {selectedConcept && (
              <div style={{ marginBottom: '10px' }}>
                <Text strong style={{ color: '#ccd6f6', marginRight: '10px' }}>关联文章:</Text>
                <Text style={{ color: '#8892b0' }}>{selectedConcept.essay_title || '无'}</Text>
              </div>
            )}
            <Divider style={{ borderColor: '#233554', margin: '10px 0' }} />
            <div style={{ maxHeight: '500px', overflow: 'auto' }}>
              <Text style={{ color: '#8892b0', fontSize: '16px', whiteSpace: 'pre-wrap', lineHeight: '1.6' }}>
                {selectedEssayContent || (selectedConcept ? '未找到关联文章内容' : '请选择一条概念数据')}
              </Text>
            </div>
          </div>
        </Card>
      </div>

      <Modal
        title={isEditing ? "编辑概念" : "新增概念"}
        visible={isModalVisible}
        width="80%"
        style={{ maxWidth: '1200px', height: '80vh' }}
        onOk={() => {
          form
            .validateFields()
            .then(handleCreateConcept)
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
        onCancel={() => setIsModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item label="概念分类" required>
            <Radio.Group
              onChange={(e) => {
                form.setFieldsValue({ 
                  category: null,
                  categoryMode: e.target.value 
                });
              }}
              defaultValue="existing"
              style={{ marginBottom: 16 }}
            >
              <Radio value="existing">选择已有分类</Radio>
              <Radio value="new">输入新分类</Radio>
            </Radio.Group>
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.categoryMode !== currentValues.categoryMode}
            >
              {({ getFieldValue }) => {
                return getFieldValue('categoryMode') === 'existing' ? (
                  <Form.Item
                    name="category"
                    rules={[{ required: true, message: '请选择概念分类' }]}
                  >
                    <Select
                      showSearch
                      placeholder="请选择概念分类"
                      options={categories.map(category => ({
                        label: category,
                        value: category,
                      }))}
                    />
                  </Form.Item>
                ) : (
                  <Form.Item
                    name="category"
                    rules={[{ required: true, message: '请输入概念分类' }]}
                  >
                    <Input placeholder="请输入新分类名称" />
                  </Form.Item>
                );
              }}
            </Form.Item>
          </Form.Item>
          <Form.Item name="concept_name" label="概念名称" rules={[{ required: true, message: '请输入概念名称' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="concept_description" label="描述" rules={[{ required: true, message: '请输入描述' }]}>
            <Input />
          </Form.Item>
          
          <Form.Item name="essay_title" label="选择文章" rules={[{ required: true, message: '请选择文章' }]}>
            <Select
              placeholder="请选择文章"
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {essays.map(essay => (
                <Option key={essay.id} value={essay.title}>{essay.title}</Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Concept;